import axios, { Axios, AxiosResponse } from "axios";
import { ResponseType } from "./type";
import { message } from "antd";
import { data } from "react-router-dom";
import { useGetToken } from "@/hooks/useHandToken";
const request = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

request.interceptors.request.use(
  (config) => {
    if (useGetToken()) config.headers.set("Authorization", useGetToken());
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

request.interceptors.response.use(
  (res: AxiosResponse): AxiosResponse<ResponseType> => {
    const resData = (res.data || {}) as ResponseType;
    const { code, data, msg } = resData;
    if (code !== 200) {
      message.error((msg || "请求失败") as string);
      throw new Error((msg || "请求失败") as string);
    }
    return resData as any;
  },
  (error) => {
    return Promise.reject(error);
  },
);
export default request;
